package cn.easier.activity.console.service.impl;

import cn.easier.activity.console.entity.*;
import cn.easier.activity.console.repository.*;
import cn.easier.activity.console.service.ActivityBargainService;
import cn.easier.activity.web.entity.ActivityInfo;
import cn.easier.activity.web.entity.ActivityPrize;
import cn.easier.activity.web.entity.PrizeType;
import cn.easier.club.base.dto.ResultInfo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 砍价ServiceImpl
 */
@Service
@Transactional
public class ActivityBargainServiceImpl implements ActivityBargainService {

    private static Logger logger = LoggerFactory.getLogger(ActivityBargainServiceImpl.class);

    private final ActivityBargainRepository activityBargainRepository;

    private final ActivityGoodsTypeRepository activityGoodsTypeRepository;

    private final BargainGoodsOrderRepository bargainGoodsOrderRepository;

    private final ActivityInfoRepository activityInfoRepository;

    private final ActivityPrizeRepository activityPrizeRepository;

    private final AdvertisingPositionRepository advertisingPositionRepository;
    //砍价商品状态
    private static final Integer DELETE_STATE = 1;

    public ActivityBargainServiceImpl(ActivityBargainRepository activityBargainRepository, ActivityGoodsTypeRepository activityGoodsTypeRepository, BargainGoodsOrderRepository bargainGoodsOrderRepository, ActivityInfoRepository activityInfoRepository, ActivityPrizeRepository activityPrizeRepository, AdvertisingPositionRepository advertisingPositionRepository) {
        this.activityBargainRepository = activityBargainRepository;
        this.activityGoodsTypeRepository = activityGoodsTypeRepository;
        this.bargainGoodsOrderRepository = bargainGoodsOrderRepository;
        this.activityInfoRepository = activityInfoRepository;
        this.activityPrizeRepository = activityPrizeRepository;
        this.advertisingPositionRepository = advertisingPositionRepository;
    }

    @Override
    public List<Object> getMessage(Integer activityId, int pageNum, int pageSize) {
        List<Object> returnList = new ArrayList<>();
        int pageCount = pageNum * pageSize;
        List<BargainGoods> byCreateBy = activityBargainRepository.findAllBy(activityId, pageCount, pageSize);
        for (BargainGoods bargainGoods : byCreateBy) {
            GoodsType one = activityGoodsTypeRepository.findOne(Integer.valueOf(bargainGoods.getGoodsType()));
            BargainGoodsParams params = new BargainGoodsParams();
            params.setActivityInfoId(bargainGoods.getActivityInfoId());
            params.setBargainNum(bargainGoods.getBargainNum());
            params.setBargainTime(bargainGoods.getBargainTime());
            params.setBeginTime(bargainGoods.getBeginTime());
            params.setBill(bargainGoods.getBill());
            params.setCreateTime(bargainGoods.getCreateTime());
            params.setDescription(bargainGoods.getDescription());
            params.setEgtid(bargainGoods.getEgtid());
            params.setEndTime(bargainGoods.getEndTime());
            params.setExchangeScore(bargainGoods.getExchangeScore());
            params.setGoodsName(bargainGoods.getGoodsName());
            params.setGoodsType(one.getSymbol());
            params.setImgSrc(bargainGoods.getImgSrc());
            params.setIsDel(bargainGoods.getIsDel());
            params.setLowestQuotation(bargainGoods.getLowestQuotation());
            params.setStock(bargainGoods.getStock());
            params.setScoreEnd(bargainGoods.getScoreEnd());
            params.setTopFlag(bargainGoods.getTopFlag());
            params.setScoreStart(bargainGoods.getScoreStart());
            params.setShareTitle(bargainGoods.getShareTitle());
            params.setShareImgUrl(bargainGoods.getShareImgUrl());
            params.setInstructions(bargainGoods.getInstructions());
            returnList.add(params);
        }
        long allByCount = activityBargainRepository.findAllByCount(activityId);
        returnList.add(allByCount);
        return returnList;
    }

    @Override
    public BargainGoods updateBargainMessage(BargainGoods params) {
        BargainGoods save = null;
        if (params.getTopFlag() == 1) {
            BargainGoods byTopFlag = activityBargainRepository.findByTopFlag(1,params.getActivityInfoId());
            if (byTopFlag != null) {
                byTopFlag.setTopFlag(0);
                activityBargainRepository.save(byTopFlag);
            }
        }
        if (params.getEgtid() != null) {
            BargainGoods one = activityBargainRepository.findOne(params.getEgtid());
            if (one != null) {
                one.setBargainNum(params.getBargainNum());
                one.setBargainTime(params.getBargainTime());
                one.setBeginTime(params.getBeginTime());
                one.setEndTime(params.getEndTime());
                one.setDescription(params.getDescription());
                one.setExchangeScore(params.getExchangeScore());
                one.setGoodsName(params.getGoodsName());
                one.setGoodsType(params.getGoodsType());
                one.setImgSrc(params.getImgSrc());
                one.setLowestQuotation(params.getLowestQuotation());
                one.setScoreEnd(params.getScoreEnd());
                one.setScoreStart(params.getScoreStart());
                one.setStock(params.getStock());
                one.setTopFlag(params.getTopFlag());
                one.setShareTitle(params.getShareTitle());
                one.setBill(params.getBill());
                one.setShareImgUrl(params.getShareImgUrl());
                one.setInstructions(params.getInstructions());
                ActivityPrize prize = activityPrizeRepository.findByActivityInfoIdAndPrizeClawType(one.getActivityInfoId(), params.getEgtid() + "");
                prize.setPrizeName(params.getGoodsName());
                prize.setPrizeNum(params.getStock());
                prize.setBill(params.getBill());
                GoodsType two = activityGoodsTypeRepository.findOne(Integer.valueOf(params.getGoodsType()));
                if (two.getSymbol().equals("RECHARGE_CARD")) {
                    prize.setPrizeGradeName("砍价商品话费");
                    prize.setPrizeName(params.getGoodsName());
                    prize.setPrizeType(PrizeType.RECHARGE_CARD);
                } else {
                    prize.setPrizeType(PrizeType.ELECTRONIC_COUPON);
                    prize.setPrizeGradeName("砍价商品劵码");
                    prize.setPrizeName(params.getGoodsName());
                    one.setBill(0);
                }
                save = activityBargainRepository.save(one);
                activityPrizeRepository.save(prize);
                return save;
            }
        }
        params.setCreateTime(new Date());
        save = activityBargainRepository.save(params);
        ActivityPrize prize = new ActivityPrize();
        prize.setPrizeNum(params.getStock());
        prize.setActivityInfoId(params.getActivityInfoId());
        prize.setBill(params.getBill());
        prize.setEffectiveTimes(10);
        prize.setPrizeGrade(1);
        String goodsType = params.getGoodsType();
        GoodsType one = activityGoodsTypeRepository.findOne(Integer.valueOf(goodsType));
        if (one.getSymbol().equals("RECHARGE_CARD")) {
            prize.setPrizeGradeName("砍价商品话费");
            prize.setPrizeName(params.getGoodsName());
            prize.setPrizeType(PrizeType.RECHARGE_CARD);
        } else {
            prize.setPrizeType(PrizeType.ELECTRONIC_COUPON);
            prize.setPrizeGradeName("砍价商品劵码");
            prize.setPrizeName(params.getGoodsName());
        }
        prize.setPrizeProbability(1.1);
        prize.setStatus(0);
        prize.setPrizeClawType(save.getEgtid() + "");
        activityPrizeRepository.save(prize);
        return save;
    }

    @Override
    public Boolean delete(Integer egtid) {
        int changeNum = activityBargainRepository.deleteGoods(DELETE_STATE, egtid);
        return changeNum > 0;
    }

    @Override
    public BargainGoods findByOne(Integer id) {
        return activityBargainRepository.findByOne(id);
    }

    @Override
    public Boolean runOrPauseOrSuperUser(Boolean flag, Integer id) {
        int changeNum = activityBargainRepository.runOrPauseOrSuperUser(flag, id);
        return changeNum > 0;
    }

    @Override
    public ResultInfo updateGoodsStock(Integer id, int goodsStock) {
        BargainGoods one = activityBargainRepository.findOne(id);
        if (one == null) {
            logger.info("未查询到商品信息--->", id);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "未查询到该商品", null);
        }
        one.setStock(goodsStock);
        BargainGoods save = activityBargainRepository.save(one);
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK),
                "商品库存修改成功", save);
    }

    @Override
    public GoodsType updateGoodsTypeMessage(GoodsType params) {
        if (params.getGtid() != null) {
            GoodsType one = activityGoodsTypeRepository.findOne(params.getGtid());
            if (one != null) {
                one.setGoodsTypeName(params.getGoodsTypeName());
                one.setSymbol(params.getSymbol());
                return activityGoodsTypeRepository.save(one);
            }
        }
        params.setCreateTime(new Date());
        return activityGoodsTypeRepository.save(params);
    }

    @Override
    public List<Object> getGoodsTypeMessage(int pageNum, int pageSize) {
        int pageCount = pageNum * pageSize;
        List<GoodsType> byCreateBy = activityGoodsTypeRepository.findAllBy(pageCount, pageSize);
        long allByCount = activityGoodsTypeRepository.findAllByCount();
        List<Object> returnList = new ArrayList<>(byCreateBy);
        returnList.add(allByCount);
        return returnList;
    }

    @Override
    public Boolean deleteGoodsType(Integer id) {
        int changeNum = activityGoodsTypeRepository.deleteGoodsType(DELETE_STATE, id);
        return changeNum > 0;
    }

    @Override
    public List<Object> getGoodsTypeSelect() {
        List<GoodsType> byIsDelete = activityGoodsTypeRepository.findByIsDelete(0);
        long allByCount = activityGoodsTypeRepository.findAllByCount();
        List<Object> returnList = new ArrayList<>(byIsDelete);
        returnList.add(allByCount);
        return returnList;
    }

    @Override
    public List<Object> getGoodsOrderMessage(int pageNum, int pageSize, Integer activityId, String phoneNum, String bargainOrderNo) {
        int pageCount = pageNum * pageSize;
        List<Object> returnList = new ArrayList<>();
        if (StringUtils.isBlank(phoneNum)) {
            phoneNum = null;
        }
        if (StringUtils.isBlank(bargainOrderNo)) {
            bargainOrderNo = null;
        }
        List<BargainGoodsOrder> byCreateBy = bargainGoodsOrderRepository.findAllBy(activityId, phoneNum, bargainOrderNo, pageCount, pageSize);
        long allByCount = bargainGoodsOrderRepository.findAllByCount(activityId, phoneNum, bargainOrderNo);
        for (BargainGoodsOrder bargainGoods : byCreateBy) {
            Integer egtid = bargainGoods.getBargainGoodsId();
            BargainGoods one = activityBargainRepository.findOne(egtid);
            BargainGoodsOrderParams params = new BargainGoodsOrderParams();
            params.setActivityId(bargainGoods.getActivityId());
            params.setAmountPayable(bargainGoods.getAmountPayable());
            params.setAttachData(bargainGoods.getAttachData());
            params.setBargainGoodsCount(bargainGoods.getBargainGoodsCount());
            params.setBargainGoodsName(one.getGoodsName());
            params.setBargainOrderNo(bargainGoods.getBargainOrderNo());
            params.setCreateTime(bargainGoods.getCreateTime());
            params.setDefinedOrderUer(bargainGoods.getDefinedOrderUer());
            params.setMemberFareAward(bargainGoods.getMemberFareAward());
            params.setRecipientPhoneNum(bargainGoods.getRecipientPhoneNum());
            params.setScore(bargainGoods.getScore());
            params.setSourceType(bargainGoods.getSourceType());
            params.setState(bargainGoods.getState());
            returnList.add(params);
        }
        returnList.add(allByCount);
        return returnList;
    }

    @Override
    public ResultInfo saveWapImg(String url, Integer activityId, String linkUrl, Integer id) {
        if (id != null) {
            AdvertisingPosition one = advertisingPositionRepository.findOne(id);
            if (one == null) {
                logger.info("未查询到商品信息--->", id);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "未查询到该广告位图片信息", null);
            } else {
                one.setLinkUrl(linkUrl);
                one.setBackgroundImage(url);
                AdvertisingPosition save = advertisingPositionRepository.save(one);
                return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK),
                        "广告位图片修改成功", one);
            }
        } else {
            AdvertisingPosition advertisingPosition = new AdvertisingPosition();
            advertisingPosition.setBackgroundImage(url);
            advertisingPosition.setLinkUrl(linkUrl);
            advertisingPosition.setTopFlag(0);
            advertisingPosition.setCreateTime(new Date());
            advertisingPosition.setIsDel(0);
            advertisingPosition.setActivityInfoId(activityId);
            AdvertisingPosition save = advertisingPositionRepository.save(advertisingPosition);
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK),
                    "广告位图片保存成功", save);
        }
    }

    @Override
    public List<Object> getAdvertisingPosition(Integer activityId, int pageNum, int pageSize) {
        List<Object> returnList = new ArrayList<>();
        int pageCount = pageNum * pageSize;
        List<AdvertisingPosition> allBy = advertisingPositionRepository.findAllBy(activityId, pageCount, pageSize);
        for (AdvertisingPosition advertisingPosition : allBy) {
            AdvertisingPositionParams params = new AdvertisingPositionParams();
            String s = advertisingPosition.getCreateTime().toString();
            String time = s.substring(0, s.indexOf("."));
            params.setActivityInfoId(advertisingPosition.getActivityInfoId());
            params.setBackgroundImage(advertisingPosition.getBackgroundImage());
            params.setCreateTime(time);
            params.setId(advertisingPosition.getId());
            params.setIsDel(advertisingPosition.getIsDel());
            params.setLinkUrl(advertisingPosition.getLinkUrl());
            params.setTopFlag(advertisingPosition.getTopFlag());
            returnList.add(params);
        }
        long allByCount = advertisingPositionRepository.findAllByCount(activityId);
        returnList.add(allByCount);
        return returnList;
    }

    @Override
    public Boolean delAdvertisingPosition(Integer id) {
        int changeNum = advertisingPositionRepository.delAdvertisingPosition(DELETE_STATE, id);
        return changeNum > 0;
    }

    @Override
    public ResultInfo topFlagAdvertisingPosition(Integer id, Integer status) {
        AdvertisingPosition one = advertisingPositionRepository.findOne(id);
        if (one == null) {
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), "未查询到该广告位图片信息", null);
        }
        if (status == 1) {
            List<AdvertisingPosition> by = advertisingPositionRepository.findBy(one.getActivityInfoId(), 0, 1);
            if (CollectionUtils.isNotEmpty(by)) {
                AdvertisingPosition advertisingPosition = by.get(0);
                advertisingPosition.setTopFlag(0);
                advertisingPositionRepository.save(advertisingPosition);
            }
            one.setTopFlag(1);
        } else if (status == 0) {
            one.setTopFlag(0);
        }
        advertisingPositionRepository.save(one);
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK),
                "操作成功", one);
    }

    @Override
    public ResultInfo getActivityList() {
        List<ActivityInfo> activityInfoList = activityInfoRepository.findByTypeIdentificationAndStatusNotOrderByCreateTimeDesc("bargain", 2);
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK),
                "获得活动成功", activityInfoList);
    }

    @Override
    public ResultInfo deletePrizeMessage(Integer id) {
        ActivityPrize activityPrize = activityPrizeRepository.findByPrizeClawTypeAndStatus(id + "", 0);
        if (activityPrize == null) {
            return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK),
                    "未查询到对应的信息", null);
        }
        activityPrize.setStatus(1);
        ActivityPrize save = activityPrizeRepository.save(activityPrize);
        return new ResultInfo(String.valueOf(HttpServletResponse.SC_OK),
                "删除商品信息成功", save);
    }

}
